﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Web.Security;
using System.Data;
using System.Data.SqlClient;
using Xceed.Wpf.Toolkit;

namespace ProjectEF6
{
    /// <summary>
    /// Interaction logic for Panel.xaml
    /// </summary>

    public partial class Panel : Window
    {
        DB db = new DB();
        public Panel()
        {
            InitializeComponent();
            tabReservaties.DataContext = db.getAllReservations();
            tabContracts.DataContext = db.getRunningContracts();
            datepickerStart.Value = DateTime.Now.AddHours(1);
            datepickerEnd.Value = DateTime.Now.AddHours(3);
            calendarReservations.SelectedDate = DateTime.Today;

            // Combobox voor locatie
            List<Location> locations = new List<Location>();
            locations = db.getAllLocations();
            foreach(Location l in locations)
            {
                cmbLocation.Items.Add(l);
            }
            cmbLocation.SelectedIndex = 0;

            // Combobox voor companies
            List<Company> companies = new List<Company>();
            companies = db.getAllCompanies();
            foreach(Company c in companies){
                cmbCompany.Items.Add(c);
            }
            cmbCompany.SelectedIndex = 0;
        }

        private void btnCreateReservation_Click(object sender, RoutedEventArgs e)
        {
           DateTime start = (DateTime)datepickerStart.Value;
           DateTime end = (DateTime)datepickerEnd.Value;
           Location l = (Location)cmbLocation.SelectedItem;
           Company c = (Company)cmbCompany.SelectedItem;

           if (checkDates(start, end, l.Id) == true && checkContract(start, end, c.Id) == true)
           {
               db.newReservation(l.Id, start, end, c.Id);
               tabReservaties.DataContext = db.getAllReservations();
           }
        }

        public Boolean checkDates(DateTime start, DateTime end, int location, int id = 0)
        {
            Boolean status = true; // true = insert mag gebeuren / false = insert mag niet gebeuren
            if (start == null || end == null)
            {
                System.Windows.MessageBox.Show("Vul een datum en tijd in.");
                status = false;
            }

            if (start >= end)
            {
                System.Windows.MessageBox.Show("De begindatum kan niet na de einddatum liggen.");
                status = false;
            }

            if (start <= DateTime.Now)
            {
                System.Windows.MessageBox.Show("De begindatum kan niet in het verleden liggen.");
                status = false;
            }

            List<reservations> reservations = new List<reservations>();
            if (id == 0) // Bij nieuwe reservatie
            {
                reservations = db.getAllReservationsOnly(location); // alle reservaties van die room ophalen
            }
            else // bij edit
            {
                reservations = db.getAllReservationsOnly(location, id);
            }
            Boolean b = false; // boolean voor overlap() method, true = messagebox met warning / false = geen warning
            foreach (reservations r in reservations)
            {
                if (start <= r.StartDate && end <= r.EndDate && end >= r.StartDate)
                {
                    b = true;
                    status = false;
                }
                if (start <= r.StartDate && end >= r.EndDate)
                {
                    b = true;
                    status = false;
                }
                if (start >= r.StartDate && end <= r.EndDate)
                {
                    b = true;
                    status = false;
                }
                if (start >= r.StartDate && start <= r.EndDate && end >= r.EndDate)
                {
                    b = true;
                    status = false;
                }
            }
            Overlap(b);
            return status;
        }

        public Boolean checkContract(DateTime start, DateTime end, int companyId, int id = 0)
        {
            Boolean b = true;
            // Info van contract van company ophalen
            List<Contract> c = new List<Contract>();
            c = db.getContractCompany(companyId);
            int maxHoursCompany = 0;
            if (c != null)
            {
                maxHoursCompany = c[0].MaxUsageHoursPerPeriod;

                // Alle reservaties van company ophalen
                List<reservations> r = new List<reservations>();
                if (id == 0) // New Reservation
                {
                    r = db.getReservationsCompany(companyId);
                }
                else // Edit Reservation
                {
                    r = db.getReservationsCompany(companyId, id);
                }

                double totHours = 0;
                double newHoursRes = 0;
                if (r != null)
                {
                    foreach (reservations res in r)
                    {
                        totHours += (res.EndDate - res.StartDate).TotalHours;
                    }
                }
                Console.WriteLine("Aantal uren zonder de nieuwe/aangepaste reservatie: " + totHours.ToString());

                // aantal uren nieuwe reservatie
                newHoursRes = (end - start).TotalHours;
                if ((totHours + newHoursRes) > maxHoursCompany)
                {
                    System.Windows.MessageBox.Show("Company met ID: " + companyId + " kan niet meer dan " + maxHoursCompany + " uren reserveren\nMet de nieuwe reservatie zal dit " + string.Format("{0:0.00}", (totHours + newHoursRes)) + " uur zijn.");
                    b = false;
                }
                Console.WriteLine("Aantal uren na de nieuwe/aangepaste reservatie: " + (totHours + newHoursRes));

                return b;
            }
            else
            {
                System.Windows.MessageBox.Show("Bedrijf met id:"+companyId+" heeft geen lopend contract!");
                b = false;
                return b;
            }
        }

        private void Overlap(Boolean b)
        {
            if (b == true)
            {
                System.Windows.MessageBox.Show("De ingegeven datum en tijd mag niet samenvallen met een bestaande reservatie.");
            }
        }

        private void btnDeleteReservation_Click(object sender, RoutedEventArgs e)
        {
            
            reservations r = (reservations)listboxReservations.SelectedItem;
            if (System.Windows.MessageBox.Show("Bent u zeker dat u reservatie met id " + r.Id + " wilt verwijderen?", "Question", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
            {
                db.deleteReservation(r.Id);
                tabReservaties.DataContext = db.getAllReservations();
            }
        }

        private void btnEditReservation_Click(object sender, RoutedEventArgs e)
        {
            reservations r = (reservations)listboxReservations.SelectedItem;
            int index = listboxReservations.SelectedIndex;
            EditReservation edit = new EditReservation(r.Id,r.StartDate,r.EndDate,r.CompanyId,r.locationId);
            edit.ShowDialog();
            // Reserveringen updaten
            tabReservaties.DataContext = db.getAllReservations();
            // Reserveringen selectie zetten op de item de bewerkt is.
            listboxReservations.SelectedIndex = index;
            // Kalender geselecteerde datum aanpassen zodat de kalender en listbox updaten (calendarReservations_SelectedDatesChanged method oproepen)
            // Verandering = Update
            calendarReservations.SelectedDate = DateTime.Now;
            calendarReservations.SelectedDate = DateTime.Today;

        }

        private void calendarReservations_SelectedDatesChanged(object sender, SelectionChangedEventArgs e)
        {
            DateTime startSelected = (DateTime)calendarReservations.SelectedDate.Value;
            DateTime endSelected = (DateTime)startSelected.AddDays(1);

            List<reservations> r = new List<reservations>();
            r = db.getReservationsFromDay(startSelected, endSelected);

            tabCalendar.DataContext = r;
        }

        private void btnStopContract_Click(object sender, RoutedEventArgs e)
        {
            Contract c = (Contract)listboxContracts.SelectedItem;
            if (System.Windows.MessageBox.Show("Bent u zeker dat u contract met id " + c.Id + " wilt stop zetten?", "Question", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
            {
                db.deleteContract(c.Id);
                tabContracts.DataContext = db.getRunningContracts();
            }
        }
        
    }
}
